﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using SmartWeigh.Model;
using SmartWeighMonitor.Utils;

namespace SmartWeigh
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public static Config config = null;
        private static object _lock = new object();
        public static GlobalVariablesModel globalVariables = null;

        private static Mutex mutex;

        public static Config GetConfig()
        {
            if (config == null)
            {
                lock (_lock)
                {
                    if (config == null)
                    {
                        config = new Config();
                    }
                }
            }
            return config;
        }
        public static GlobalVariablesModel getGlobalVariables()
        {
            if (globalVariables == null)
            {
                lock (_lock)
                {
                    if (globalVariables == null)
                    {
                        globalVariables = new GlobalVariablesModel();
                    }
                }
            }
            return globalVariables;
        }
        protected override void OnStartup(StartupEventArgs e)
        {
           // mutex = new Mutex(true, "Channel2", out bool ret);//判断是否开启一个程序
            /*if (!ret)
            {
                MessageBox.Show("程序已经打开");
                Environment.Exit(0);
            }*/

            base.OnStartup(e);

            RegisterEvents();
            App.GetConfig().DeviceCode = ConfigurationManager.AppSettings["DeviceCode"];
            App.GetConfig().DeviceName = ConfigurationManager.AppSettings["DeviceName"];
            App.GetConfig().DeviceType = ConfigurationManager.AppSettings["DeviceType"];

            App.GetConfig().Mq_HostName = ConfigurationManager.AppSettings["Mq_HostName"];
            App.GetConfig().Mq_UserName = ConfigurationManager.AppSettings["Mq_UserName"];
            App.GetConfig().Mq_Password = ConfigurationManager.AppSettings["Mq_Password"];

            App.GetConfig().VideoUrl01 = ConfigurationManager.AppSettings["VideoUrl01"];
            App.GetConfig().VideoUrl02 = ConfigurationManager.AppSettings["VideoUrl02"];

            App.GetConfig().HttpServerIp = ConfigurationManager.AppSettings["HttpServerIp"];
            App.GetConfig().HttpServerPort = ConfigurationManager.AppSettings["HttpServerPort"];
            App.GetConfig().AuthHttpServerPort = ConfigurationManager.AppSettings["AuthHttpServerPort"];
            App.GetConfig().ImagePath = ConfigurationManager.AppSettings["ImagePath"];
            App.GetConfig().PersonVideo_URL = ConfigurationManager.AppSettings["PersonVideo_URL"];
            App.GetConfig().PersonVideo_Username = ConfigurationManager.AppSettings["PersonVideo_Username"];
            App.GetConfig().PersonVideo_Password = ConfigurationManager.AppSettings["PersonVideo_Password"];

            App.GetConfig().HikVideo_URL1 = ConfigurationManager.AppSettings["HikVideo_URL1"];
            App.GetConfig().HikVideo_URL2 = ConfigurationManager.AppSettings["HikVideo_URL2"];

            App.GetConfig().HikVideo_Port = ConfigurationManager.AppSettings["HikVideo_Port"];
            App.GetConfig().HikVideo_Username = ConfigurationManager.AppSettings["HikVideo_Username"];
            App.GetConfig().HikVideo_Password = ConfigurationManager.AppSettings["HikVideo_Password"];
            App.GetConfig().IfReturnCard = ConfigurationManager.AppSettings["IfReturnCard"];

            App.GetConfig().ImageSavePath = ConfigurationManager.AppSettings["ImageSavePath"];
            App.GetConfig().SettingPassword= ConfigurationManager.AppSettings["SettingPassword"];
            App.GetConfig().Printer001 = ConfigurationManager.AppSettings["Printer001"];
            App.GetConfig().Printer002 = ConfigurationManager.AppSettings["Printer002"];
            App.GetConfig().Nodered_Ip = ConfigurationManager.AppSettings["Nodered_Ip"];
            App.GetConfig().Nodered_Port = ConfigurationManager.AppSettings["Nodered_Port"];

        }

        private void RegisterEvents()
        {
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            //UI线程未捕获异常处理事件（UI主线程）
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        }


        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            try
            {
                var exception = e.Exception as Exception;
                if (exception != null)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
            }
        }

        //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)      
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                var exception = e.ExceptionObject as Exception;
                if (exception != null)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                //ignore
            }
        }

        //UI线程未捕获异常处理事件（UI主线程）
        private static void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                HandleException(e.Exception);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                //处理完后，我们需要将Handler=true表示已此异常已处理过
                e.Handled = true;
            }
        }
        private static void HandleException(Exception e)
        {
            //将异常信息写入到日志文件
            FileUtil.Log(e.ToString());
        }


    }
}
